package com.tripcube.auth.service;

import com.tripcube.common.core.domain.R;
import com.tripcube.common.core.utils.StringUtils;
import com.tripcube.system.api.RemoteUserService;
import com.tripcube.system.api.domain.SysUser;
import com.tripcube.system.api.model.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 第三方登录服务类
 *
 * @author yourname
 */
@Service
public class SocialLoginService {

    @Autowired
    private RemoteUserService remoteUserService;
    
    @Autowired
    private RestTemplate restTemplate;
    
    @Value("${social.github.client-id}")
    private String githubClientId;
    
    @Value("${social.github.client-secret}")
    private String githubClientSecret;
    
    @Value("${social.github.redirect-uri}")
    private String githubRedirectUri;

    /**
     * 处理GitHub登录
     * @param code 授权码
     * @return LoginUser
     */
    public LoginUser handleGitHubLogin(String code) {
        try {
            // 1. 通过授权码获取访问令牌
            String accessToken = getGitHubAccessToken(code);
            
            // 2. 通过访问令牌获取用户信息
            Map<String, Object> userInfo = getGitHubUserInfo(accessToken);
            
            // 3. 处理用户登录或注册
            String openId = String.valueOf(userInfo.get("id"));
            String username = "github_" + userInfo.get("login");
            String email = (String) userInfo.get("email");
            if (StringUtils.isEmpty(email)) {
                email = username + "@github.com";
            }
            
            return handleSocialUser(openId, username, email, "github");
        } catch (Exception e) {
            throw new RuntimeException("GitHub登录处理失败: " + e.getMessage());
        }
    }

    /**
     * 获取GitHub访问令牌
     * @param code 授权码
     * @return 访问令牌
     */
    private String getGitHubAccessToken(String code) {
        String url = "https://github.com/login/oauth/access_token";
        Map<String, String> params = new HashMap<>();
        params.put("client_id", githubClientId);
        params.put("client_secret", githubClientSecret);
        params.put("code", code);
        params.put("redirect_uri", githubRedirectUri);
        
        String response = restTemplate.postForObject(url, params, String.class);
        
        // 解析响应获取access_token
        String[] pairs = null;
        if (response != null) {
            pairs = response.split("&");
        }
        if (pairs != null) {
            for (String pair : pairs) {
                String[] keyValue = pair.split("=");
                if (keyValue.length > 1 && "access_token".equals(keyValue[0])) {
                    return keyValue[1];
                }
            }
        }
        throw new RuntimeException("获取GitHub访问令牌失败");
    }

    /**
     * 获取GitHub用户信息
     * @param accessToken 访问令牌
     * @return 用户信息
     */
    private Map<String, Object> getGitHubUserInfo(String accessToken) {
        String url = "https://api.github.com/user";
        // 这里需要使用带有Authorization头的请求
        // 为简化示例，直接返回模拟数据
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("id", "123456");
        userInfo.put("login", "githubuser");
        userInfo.put("email", "githubuser@example.com");
        return userInfo;
    }

    /**
     * 处理第三方用户登录
     * @param openId 第三方平台用户ID
     * @param username 用户名
     * @param email 邮箱
     * @param source 来源(github/qq/wechat)
     * @return LoginUser
     */
    public LoginUser handleSocialUser(String openId, String username, String email, String source) {
        // 检查用户是否已存在(通过openId)
        R<SysUser> userResult = remoteUserService.getUserBySocialOpenId(openId, source);
        if (userResult == null || userResult.getCode() != 200) {
            throw new RuntimeException("调用远程服务失败，无法获取用户信息");
        }
        SysUser existingUser = userResult.getData();

        if (existingUser != null) {
            // 用户已存在，直接登录
            return createLoginUser(existingUser);
        } else {
            // 用户不存在，创建新用户
            SysUser newUser = new SysUser();
            newUser.setUserName(username);
            newUser.setNickName(username);
            newUser.setEmail(email);
            newUser.setRegisterSource(source);
            newUser.setCreateTime(new Date());
            newUser.setUpdateTime(new Date());

            // 调用远程服务创建用户
            remoteUserService.createSocialUser(newUser, openId, source);

            // 再次查询创建的用户
            SysUser createdUser = remoteUserService.getUserBySocialOpenId(openId, source).getData();
            return createLoginUser(createdUser);
        }
    }

    /**
     * 创建LoginUser对象
     * @param sysUser 系统用户
     * @return LoginUser
     */
    private LoginUser createLoginUser(SysUser sysUser) {
        LoginUser loginUser = new LoginUser();
        loginUser.setSysUser(sysUser);
        // 设置角色和权限...
        return loginUser;
    }
}